import {ipcRenderer} from 'electron';

import util from './common/util';
import store from './store';
import {createView} from './views';
import {IDesign} from './types/IDesign';
import {IParentView} from './types/IParentView';
import {ActionType} from './store/ActionType';

ipcRenderer.on('new-file', () => {
  const designId = util.generateId('d');
  const rootView = createView('div', designId) as IParentView;
  rootView.style = {
    width: '1024px',
    height: '600px',
    background: '#fff',
    margin: 'auto'
  };

  ipcRenderer.send('add-design', designId);

  _addDesign({
    id: designId,
    root: rootView
  });
  _updateDesignName(designId, 'untitled');
});

ipcRenderer.on('open-file', (event: any, design: IDesign, filename: string) => {
  if (design) {
    _addDesign(design);
    _updateDesignName(design.id, filename);
  }
});

ipcRenderer.on('save-file', () => {
  const activeDesign = _getActiveDesign();
  if (activeDesign) {
    ipcRenderer.send('save-file', activeDesign);
  }
});

ipcRenderer.on('saved-file', (event: any, designId: string, filename: string) => {
  _updateDesignName(designId, filename);
});

ipcRenderer.on('save-as-view', () => {
  const activeDesign = _getActiveDesign();
  if (activeDesign) {
    ipcRenderer.send('save-as-view', activeDesign);
  }
});

ipcRenderer.on('load-views', (event, views) => {
  if (!views || views.length === 0) {
    return;
  }

  _addWidgets(views);
});

function _addDesign(design: IDesign) {
  store.dispatch({
    type: ActionType.ADD_DESIGN,
    design
  });
}

function _updateDesignName(designId: string, designName: string) {
  store.dispatch({
    type: ActionType.UPDATE_DESIGN_NAME,
    designId,
    designName
  });
}

function _getActiveDesign() {
  const appState = store.getState();
  const {designIdsState, designsState, activeDesignState} = appState;

  const activeDesignId = activeDesignState.active;
  return designsState[activeDesignId] || designsState[designIdsState[0]];
}

function _addWidgets(widgets) {
  store.dispatch({
    type: ActionType.LOADED_WIDGETS,
    widgets
  });
}

ipcRenderer.send('load-views');
